// 全局变量
let todos = []; // 待办事项数组
let dailyTasks = {}; // 每日工作记录对象，键为日期
let tags = []; // 标签数组
let currentDate = new Date(); // 当前选中的日期
let currentView = 'todo'; // 当前视图
let selectedWorkTagId = null; // 当前选中的工作标签ID
let selectedTags = []; // 月度看板中选中的标签ID数组

// DOM元素引用
const tabBtns = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');
const todoInput = document.getElementById('todoInput');
const addTodoBtn = document.getElementById('addTodoBtn');
const todoList = document.getElementById('todoList');
const currentDateDisplay = document.getElementById('currentDate');
const prevDayBtn = document.getElementById('prevDay');
const nextDayBtn = document.getElementById('nextDay');
const todayBtn = document.getElementById('todayBtn');
const workInput = document.getElementById('workInput');
const addWorkBtn = document.getElementById('addWorkBtn');
const dailyWorkList = document.getElementById('dailyWorkList');
const currentMonthDisplay = document.getElementById('currentMonth');
const prevMonthBtn = document.getElementById('prevMonth');
const nextMonthBtn = document.getElementById('nextMonth');
const currentMonthBtn = document.getElementById('currentMonthBtn');
const exportBtn = document.getElementById('exportBtn');
const filterTagsList = document.getElementById('filterTagsList');
const calendarGrid = document.getElementById('calendarGrid');
const statsContainer = document.getElementById('statsContainer');
const monthlyRecordsList = document.getElementById('monthlyRecordsList');
const tagNameInput = document.getElementById('tagNameInput');
const tagColorInput = document.getElementById('tagColorInput');
const addTagBtn = document.getElementById('addTagBtn');
const tagList = document.getElementById('tagList');
const workTagsList = document.getElementById('workTagsList');
const selectedWorkTagDisplay = document.getElementById('selectedWorkTagDisplay');
const importBtn = document.getElementById('importBtn');
const importFile = document.getElementById('importFile');

// 初始化应用
function initApp() {
    // 加载本地存储的数据
    loadData();
    
    // 如果是首次使用，添加默认标签
    if (tags.length === 0) {
        // 默认提供5种标签，但界面上保留8种颜色选项供用户选择
        const defaultTags = [
            { id: Date.now() + 1, name: '教学', color: '#4CAF50' },
            { id: Date.now() + 2, name: '科研', color: '#2196F3' },
            { id: Date.now() + 3, name: '兼职', color: '#FF9800' },
            { id: Date.now() + 4, name: '运动', color: '#9C27B0' },
            { id: Date.now() + 5, name: '其它', color: '#F44336' }
        ];
        tags = defaultTags;
        saveData();
    }

    // 初始化视图
    updateDateDisplay();
    updateMonthDisplay();
    renderTodoList();
    renderWorkTags();
    renderDailyWorkList();
    renderCalendar();
    renderFilterTags();
    renderMonthlyRecords();
    updateMonthlyStats();
    renderTagList();

    // 添加事件监听器
    setupEventListeners();
}

// 设置事件监听器
function setupEventListeners() {
    // 标签页切换
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const tab = btn.dataset.tab;
            switchTab(tab);
        });
    });

    // 待办事项
    addTodoBtn.addEventListener('click', addTodo);
    todoInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addTodo();
    });

    // 每日工作日期导航
    prevDayBtn.addEventListener('click', () => {
        currentDate.setDate(currentDate.getDate() - 1);
        updateDateDisplay();
        renderDailyWorkList();
    });

    nextDayBtn.addEventListener('click', () => {
        currentDate.setDate(currentDate.getDate() + 1);
        updateDateDisplay();
        renderDailyWorkList();
    });

    todayBtn.addEventListener('click', () => {
        currentDate = new Date();
        updateDateDisplay();
        renderDailyWorkList();
    });

    // 添加工作记录
    addWorkBtn.addEventListener('click', addWork);
    workInput.addEventListener('keypress', (e) => {
        // 使用Shift+Enter提交，单独Enter键用于换行
        if (e.key === 'Enter' && e.shiftKey) {
            e.preventDefault(); // 阻止默认的换行行为
            addWork();
        }
    });

    // 月度视图日期导航
    prevMonthBtn.addEventListener('click', () => {
        currentDate.setMonth(currentDate.getMonth() - 1);
        updateMonthDisplay();
        renderCalendar();
        renderMonthlyRecords();
        updateMonthlyStats();
    });

    nextMonthBtn.addEventListener('click', () => {
        currentDate.setMonth(currentDate.getMonth() + 1);
        updateMonthDisplay();
        renderCalendar();
        renderMonthlyRecords();
        updateMonthlyStats();
    });

    currentMonthBtn.addEventListener('click', () => {
        currentDate = new Date();
        updateMonthDisplay();
        renderCalendar();
        renderMonthlyRecords();
        updateMonthlyStats();
    });

    // 导出数据
    exportBtn.addEventListener('click', exportData);
    
    // 导入数据
    importBtn.addEventListener('click', () => {
        importFile.click();
    });
    
    importFile.addEventListener('change', importData);

    // 添加标签
    addTagBtn.addEventListener('click', addNewTag);
    tagNameInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addNewTag();
    });
    
    // 颜色按钮点击事件
    document.addEventListener('DOMContentLoaded', () => {
        const colorBtns = document.querySelectorAll('.color-btn');
        const tagColorInput = document.getElementById('tagColorInput');
        
        colorBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                // 移除所有按钮的选中状态
                colorBtns.forEach(b => b.classList.remove('selected'));
                // 为当前点击的按钮添加选中状态
                btn.classList.add('selected');
                // 更新隐藏输入框的值
                const color = btn.dataset.color;
                tagColorInput.value = color;
            });
        });
    });
}

// 切换标签页
function switchTab(tab) {
    currentView = tab;
    
    // 更新标签页按钮状态
    tabBtns.forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.tab === tab) {
            btn.classList.add('active');
        }
    });

    // 更新标签页内容显示
    tabContents.forEach(content => {
        content.classList.remove('active');
        if (content.id === tab) {
            content.classList.add('active');
        }
    });

    // 根据当前视图更新数据
    if (tab === 'daily') {
        // 修复bug：切换到每日工作页面时，重置currentDate为当天日期
        currentDate = new Date();
        updateDateDisplay();
        renderDailyWorkList();
        renderWorkTags();
    } else if (tab === 'monthly') {
        // 修复bug：切换到月度看板时，更新月份显示
        updateMonthDisplay();
        renderCalendar();
        renderFilterTags();
        renderMonthlyRecords();
        updateMonthlyStats();
    } else if (tab === 'settings') {
        renderTagList();
    }
}

// 更新日期显示
function updateDateDisplay() {
    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    currentDateDisplay.textContent = currentDate.toLocaleDateString('zh-CN', options);
}

// 更新月份显示
function updateMonthDisplay() {
    const options = { year: 'numeric', month: 'long' };
    currentMonthDisplay.textContent = currentDate.toLocaleDateString('zh-CN', options);
}

// 格式化日期为YYYY-MM-DD格式
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 加载数据
function loadData() {
    const savedTodos = localStorage.getItem('todos');
    const savedDailyTasks = localStorage.getItem('dailyTasks');
    const savedTags = localStorage.getItem('tags');
    
    if (savedTodos) {
        todos = JSON.parse(savedTodos);
    }
    
    if (savedDailyTasks) {
        dailyTasks = JSON.parse(savedDailyTasks);
    }
    
    if (savedTags) {
        tags = JSON.parse(savedTags);
    }
}

// 保存数据
function saveData() {
    localStorage.setItem('todos', JSON.stringify(todos));
    localStorage.setItem('dailyTasks', JSON.stringify(dailyTasks));
    localStorage.setItem('tags', JSON.stringify(tags));
}

// 添加待办事项
function addTodo() {
    const text = todoInput.value.trim();
    if (text) {
        const todo = {
            id: Date.now(),
            text,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        todos.push(todo);
        saveData();
        renderTodoList();
        todoInput.value = '';
    }
}

// 渲染待办事项列表
function renderTodoList() {
    todoList.innerHTML = '';
    
    todos.forEach(todo => {
        const todoItem = document.createElement('div');
        todoItem.className = 'todo-item';
        todoItem.dataset.id = todo.id;
        
        const todoContent = document.createElement('div');
        todoContent.className = 'todo-content';
        todoContent.textContent = todo.text;
        if (todo.completed) {
            todoContent.style.textDecoration = 'line-through';
            todoContent.style.color = '#888';
        }
        
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.textContent = '删除';
        deleteBtn.addEventListener('click', () => deleteTodo(todo.id));
        
        todoItem.appendChild(todoContent);
        todoItem.appendChild(deleteBtn);
        
        // 点击待办事项切换完成状态
        todoItem.addEventListener('click', (e) => {
            if (e.target !== deleteBtn) {
                toggleTodoCompleted(todo.id);
            }
        });
        
        todoList.appendChild(todoItem);
    });
}

// 切换待办事项完成状态
function toggleTodoCompleted(id) {
    const todo = todos.find(todo => todo.id === id);
    if (todo) {
        todo.completed = !todo.completed;
        saveData();
        renderTodoList();
    }
}

// 删除待办事项
function deleteTodo(id) {
    todos = todos.filter(todo => todo.id !== id);
    saveData();
    renderTodoList();
}

// 添加工作记录
function addWork() {
    const text = workInput.value.trim();
    
    if (text) {
        const dateKey = formatDate(currentDate);
        const tag = selectedWorkTagId ? tags.find(t => t.id === selectedWorkTagId) : null;
        
        const newTask = {
            id: Date.now().toString(),
            text,
            tag: tag ? tag.name : '',
            tagColor: tag ? tag.color : '',
            tagId: selectedWorkTagId || null,
            timestamp: new Date().toISOString()
        };
        
        if (!dailyTasks[dateKey]) {
            dailyTasks[dateKey] = [];
        }
        
        dailyTasks[dateKey].push(newTask);
        saveData();
        renderDailyWorkList();
        
        workInput.value = '';
        selectedWorkTagId = null;
        renderWorkTags();
        
        // 如果当前是月度视图，更新日历和记录
        if (currentView === 'monthly') {
            renderCalendar();
            renderMonthlyRecords();
            updateMonthlyStats();
        }
    }
}

// 渲染每日工作列表
function renderDailyWorkList() {
    dailyWorkList.innerHTML = '';
    const dateKey = formatDate(currentDate);
    const tasks = dailyTasks[dateKey] || [];
    
    tasks.forEach(task => {
        const workItem = document.createElement('div');
        workItem.className = 'work-item';
        workItem.dataset.id = task.id;
        
        const workContent = document.createElement('div');
        workContent.className = 'work-content';
        workContent.textContent = task.text;
        
        const tagSpan = document.createElement('span');
        tagSpan.className = 'work-tag';
        tagSpan.textContent = task.tag;
        tagSpan.style.backgroundColor = task.tagColor;
        
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.textContent = '删除';
        deleteBtn.addEventListener('click', () => deleteWork(dateKey, task.id));
        
        workContent.appendChild(tagSpan);
        workItem.appendChild(workContent);
        workItem.appendChild(deleteBtn);
        
        dailyWorkList.appendChild(workItem);
    });
}

// 删除每日工作
function deleteWork(dateKey, id) {
    if (dailyTasks[dateKey]) {
        dailyTasks[dateKey] = dailyTasks[dateKey].filter(task => task.id !== id);
        // 如果当天没有记录了，删除该日期键
        if (dailyTasks[dateKey].length === 0) {
            delete dailyTasks[dateKey];
        }
        saveData();
        renderDailyWorkList();
        
        // 如果当前是月度视图，更新日历和记录
        if (currentView === 'monthly') {
            renderCalendar();
            renderMonthlyRecords();
            updateMonthlyStats();
        }
    }
}

// 渲染每日工作页面的标签选择区域
function renderWorkTags() {
    workTagsList.innerHTML = '';
    selectedWorkTagDisplay.innerHTML = '';
    
    tags.forEach(tag => {
        const tagItem = document.createElement('div');
        tagItem.className = 'work-tag-item';
        tagItem.textContent = tag.name;
        tagItem.style.backgroundColor = tag.color;
        tagItem.style.color = 'white';
        
        // 如果标签已被选中，添加选中样式
        if (selectedWorkTagId === tag.id) {
            tagItem.classList.add('selected');
        }
        
        // 点击标签切换选中状态
        tagItem.addEventListener('click', () => {
            // 如果点击的是当前选中的标签，则取消选择
            if (selectedWorkTagId === tag.id) {
                selectedWorkTagId = null;
                renderWorkTags();
                return;
            }
            
            // 否则选中该标签
            selectedWorkTagId = tag.id;
            renderWorkTags();
        });
        
        workTagsList.appendChild(tagItem);
    });
    
    // 如果没有标签，显示提示信息
    if (tags.length === 0) {
        const noTagsMsg = document.createElement('p');
        noTagsMsg.className = 'no-tags-message';
        noTagsMsg.textContent = '暂无标签，请先在设置页面添加标签';
        workTagsList.appendChild(noTagsMsg);
    }
    
    // 显示当前选中的标签
    if (selectedWorkTagId) {
        const selectedTag = tags.find(tag => tag.id === selectedWorkTagId);
        if (selectedTag) {
            const selectedTagEl = document.createElement('div');
            selectedTagEl.className = 'selected-tag';
            selectedTagEl.innerHTML = `
                <span style="background-color: ${selectedTag.color}; color: white;">${selectedTag.name}</span>
                <button class="remove-tag-btn">×</button>
            `;
            
            // 添加移除标签的事件监听
            selectedTagEl.querySelector('.remove-tag-btn').addEventListener('click', () => {
                selectedWorkTagId = null;
                renderWorkTags();
            });
            
            selectedWorkTagDisplay.appendChild(selectedTagEl);
        }
    }
}

// 渲染筛选标签
function renderFilterTags() {
    filterTagsList.innerHTML = '';
    
    tags.forEach(tag => {
        const filterTag = document.createElement('div');
        filterTag.className = 'filter-tag';
        filterTag.textContent = tag.name;
        filterTag.style.backgroundColor = tag.color;
        filterTag.style.color = 'white';
        
        // 如果标签已选中，添加选中样式
        if (selectedTags.includes(tag.id)) {
            filterTag.classList.add('selected');
        }
        
        // 点击标签切换选中状态
        filterTag.addEventListener('click', () => {
            const index = selectedTags.indexOf(tag.id);
            if (index > -1) {
                selectedTags.splice(index, 1);
                filterTag.classList.remove('selected');
            } else {
                selectedTags.push(tag.id);
                filterTag.classList.add('selected');
            }
            
            renderCalendar(); // 重新渲染日历，显示筛选后的标签事件点
            renderMonthlyRecords();
            updateMonthlyStats();
        });
        
        filterTagsList.appendChild(filterTag);
    });
}

// 渲染标签列表（设置页面）
function renderTagList() {
    tagList.innerHTML = '';
    
    tags.forEach(tag => {
        const tagItem = document.createElement('div');
        tagItem.className = 'tag-item';
        
        const tagName = document.createElement('span');
        tagName.className = 'tag-name';
        tagName.textContent = tag.name;
        
        const tagColor = document.createElement('div');
        tagColor.className = 'tag-color';
        tagColor.style.backgroundColor = tag.color;
        
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.textContent = '删除';
        deleteBtn.addEventListener('click', () => deleteTag(tag.id));
        
        tagItem.appendChild(tagName);
        tagItem.appendChild(tagColor);
        tagItem.appendChild(deleteBtn);
        
        tagList.appendChild(tagItem);
    });
}

// 添加新标签
function addNewTag() {
    const name = tagNameInput.value.trim();
    const color = tagColorInput.value;
    
    if (name) {
        // 检查标签名是否已存在
        if (tags.some(tag => tag.name === name)) {
            alert('标签名称已存在！');
            return;
        }
        
        const newTag = {
            id: Date.now(),
            name,
            color
        };
        
        tags.push(newTag);
        saveData();
        renderTagList();
        renderWorkTags();
        renderFilterTags();
        
        // 如果当前是月度视图，更新统计
        if (currentView === 'monthly') {
            updateMonthlyStats();
        }
        
        tagNameInput.value = '';
    }
}

// 删除标签
function deleteTag(id) {
    // 不允许删除最后一个标签
    if (tags.length <= 1) {
        alert('至少需要保留一个标签！');
        return;
    }
    
    // 从标签列表中删除
    tags = tags.filter(tag => tag.id !== id);
    
    // 从选中标签中移除
    selectedTags = selectedTags.filter(tagId => tagId !== id);
    
    // 移除所有使用该标签的工作记录的标签
    for (const dateKey in dailyTasks) {
        dailyTasks[dateKey].forEach(task => {
            if (task.tagId === id) {
                task.tag = '';
                task.tagColor = '';
                task.tagId = null;
            }
        });
    }
    
    // 如果删除的是当前选中的标签，重置选择
    if (selectedWorkTagId === id) {
        selectedWorkTagId = null;
    }
    
    saveData();
    renderTagList();
    renderWorkTags();
    renderFilterTags();
    
    // 更新所有相关视图
    renderDailyWorkList();
    if (currentView === 'monthly') {
        renderCalendar();
        renderMonthlyRecords();
        updateMonthlyStats();
    }
}

// 渲染日历
function renderCalendar() {
    calendarGrid.innerHTML = '';
    
    // 添加星期标题
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    weekDays.forEach(day => {
        const dayHeader = document.createElement('div');
        dayHeader.className = 'calendar-weekday';
        dayHeader.textContent = day;
        dayHeader.style.textAlign = 'center';
        dayHeader.style.fontWeight = 'bold';
        dayHeader.style.padding = '10px 0';
        dayHeader.style.color = '#666';
        calendarGrid.appendChild(dayHeader);
    });
    
    // 获取当前月份的第一天
    const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    // 获取当前月份的最后一天
    const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
    // 获取第一天是星期几（0-6，0是星期日）
    const startDayOfWeek = firstDay.getDay();
    // 获取上个月的最后一天
    const prevMonthLastDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate();
    // 获取当前月份的总天数
    const daysInMonth = lastDay.getDate();
    
    // 添加上个月的日期（用于填充日历第一行）
    for (let i = startDayOfWeek - 1; i >= 0; i--) {
        const day = document.createElement('div');
        day.className = 'calendar-day other-month';
        day.textContent = prevMonthLastDay - i;
        calendarGrid.appendChild(day);
    }
    
    // 添加当前月份的日期
    for (let i = 1; i <= daysInMonth; i++) {
        const day = document.createElement('div');
        day.className = 'calendar-day';
        day.textContent = i;
        
        // 检查是否是今天
        const today = new Date();
        if (i === today.getDate() && 
            currentDate.getMonth() === today.getMonth() && 
            currentDate.getFullYear() === today.getFullYear()) {
            day.classList.add('today');
        }
        
        // 检查是否有工作记录
        const dateKey = formatDate(new Date(currentDate.getFullYear(), currentDate.getMonth(), i));
        if (dailyTasks[dateKey]) {
            const tasks = dailyTasks[dateKey];
            
            // 应用标签筛选
            const filteredTasks = selectedTags.length > 0 
                ? tasks.filter(task => {
                    const tag = task.tagId ? tags.find(t => t.id === task.tagId) : null;
                    // 如果没有tagId，尝试通过tag名称查找
                    if (!tag && task.tag) {
                        const nameTag = tags.find(t => t.name === task.tag);
                        return nameTag && selectedTags.includes(nameTag.id);
                    }
                    return tag && selectedTags.includes(tag.id);
                  })
                : tasks;
            
            // 添加记录点
            if (filteredTasks.length > 0) {
                const dotsContainer = document.createElement('div');
                dotsContainer.className = 'record-dots';
                
                // 为每个任务添加一个点，最多显示5个点
                const displayDots = Math.min(filteredTasks.length, 5);
                for (let j = 0; j < displayDots; j++) {
                    const dot = document.createElement('div');
                    dot.className = 'record-dot';
                    dot.style.backgroundColor = filteredTasks[j].tagColor;
                    dotsContainer.appendChild(dot);
                }
                
                day.appendChild(dotsContainer);
            }
        }
        
        // 点击日期可以查看当天的详细记录
        day.addEventListener('click', () => {
            // 如果点击的是其他月份的日期，切换到该月份
            if (day.classList.contains('other-month')) {
                const targetDate = new Date(currentDate.getFullYear(), 
                    i > prevMonthLastDay/2 ? currentDate.getMonth() - 1 : currentDate.getMonth() + 1,
                    parseInt(day.textContent));
                currentDate = targetDate;
                updateMonthDisplay();
                renderCalendar();
                renderMonthlyRecords();
                updateMonthlyStats();
            }
        });
        
        calendarGrid.appendChild(day);
    }
}

// 渲染月度工作记录
function renderMonthlyRecords() {
    monthlyRecordsList.innerHTML = '';
    
    // 获取当前月份的所有日期键
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const monthKey = `${year}-${String(month + 1).padStart(2, '0')}`;
    
    // 过滤出当前月份的记录
    const monthlyRecords = {};
    for (const dateKey in dailyTasks) {
        if (dateKey.startsWith(monthKey)) {
            monthlyRecords[dateKey] = dailyTasks[dateKey];
        }
    }
    
    // 如果没有记录
    if (Object.keys(monthlyRecords).length === 0) {
        const emptyMsg = document.createElement('div');
        emptyMsg.textContent = '本月暂无工作记录';
        emptyMsg.style.textAlign = 'center';
        emptyMsg.style.padding = '20px';
        emptyMsg.style.color = '#888';
        monthlyRecordsList.appendChild(emptyMsg);
        return;
    }
    
    // 按日期排序并渲染记录
    const sortedDates = Object.keys(monthlyRecords).sort();
    
    sortedDates.forEach(dateKey => {
        const tasks = monthlyRecords[dateKey];
        
        // 应用标签筛选
        const filteredTasks = selectedTags.length > 0 
            ? tasks.filter(task => {
                const tag = tags.find(t => t.name === task.tag);
                return tag && selectedTags.includes(tag.id);
              })
            : tasks;
        
        if (filteredTasks.length === 0) return;
        
        // 创建日期标题
        const dateTitle = document.createElement('h4');
        const date = new Date(dateKey);
        dateTitle.textContent = date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric', weekday: 'long' });
        dateTitle.style.margin = '20px 0 10px 0';
        monthlyRecordsList.appendChild(dateTitle);
        
        // 创建记录容器
        const dateRecords = document.createElement('div');
        dateRecords.className = 'monthly-records-list';
        
        filteredTasks.forEach(task => {
            const recordItem = document.createElement('div');
            recordItem.className = 'record-item';
            
            const recordContent = document.createElement('div');
            recordContent.className = 'record-content';
            // 将文本中的换行符转换为HTML的<br>标签，以实现正确的分段显示
            recordContent.innerHTML = task.text.replace(/\n/g, '<br>');
            
            const tagSpan = document.createElement('span');
            tagSpan.className = 'work-tag';
            tagSpan.textContent = task.tag;
            tagSpan.style.backgroundColor = task.tagColor;
            
            recordContent.appendChild(tagSpan);
            recordItem.appendChild(recordContent);
            
            dateRecords.appendChild(recordItem);
        });
        
        monthlyRecordsList.appendChild(dateRecords);
    });
}

// 更新月度统计
function updateMonthlyStats() {
    statsContainer.innerHTML = '';
    
    // 获取当前月份的所有记录
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const monthKey = `${year}-${String(month + 1).padStart(2, '0')}`;
    
    // 统计每个标签的记录数
    const tagStats = {};
    let totalRecords = 0;
    
    for (const dateKey in dailyTasks) {
        if (dateKey.startsWith(monthKey)) {
            const tasks = dailyTasks[dateKey];
            
            tasks.forEach(task => {
                const tag = tags.find(t => t.name === task.tag);
                if (tag) {
                    // 应用标签筛选
                    if (selectedTags.length === 0 || selectedTags.includes(tag.id)) {
                        tagStats[tag.id] = (tagStats[tag.id] || 0) + 1;
                        totalRecords++;
                    }
                }
            });
        }
    }
    
    // 创建总记录数统计项
    const totalStatItem = document.createElement('div');
    totalStatItem.className = 'stat-item';
    totalStatItem.innerHTML = `
        <span>总记录数</span>
        <span>${totalRecords}</span>
    `;
    statsContainer.appendChild(totalStatItem);
    
    // 创建每个标签的统计项
    tags.forEach(tag => {
        // 应用标签筛选
        if (selectedTags.length === 0 || selectedTags.includes(tag.id)) {
            const count = tagStats[tag.id] || 0;
            const statItem = document.createElement('div');
            statItem.className = 'stat-item';
            statItem.innerHTML = `
                <span style="display: inline-block; width: 12px; height: 12px; background-color: ${tag.color}; border-radius: 50%; margin-right: 5px;"></span>
                <span>${tag.name}</span>
                <span>${count}</span>
            `;
            statsContainer.appendChild(statItem);
        }
    });
}

// 导出数据
function exportData() {
    // 创建导出数据对象
    const exportData = {
        todos,
        dailyTasks,
        tags,
        exportDate: new Date().toISOString()
    };
    
    // 将数据转换为JSON字符串
    const jsonStr = JSON.stringify(exportData, null, 2);
    
    // 创建Blob对象
    const blob = new Blob([jsonStr], { type: 'application/json' });
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    
    // 设置文件名，包含当前日期
    const date = new Date();
    const fileName = `工作记录_${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}.json`;
    a.download = fileName;
    
    // 触发下载
    a.click();
    
    // 清理URL对象
    URL.revokeObjectURL(url);
}

// 导入数据
function importData(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    // 检查文件类型
    if (!file.name.endsWith('.json')) {
        alert('请选择JSON格式的文件！');
        return;
    }
    
    // 确认导入操作（会覆盖现有数据）
    if (!confirm('确定要导入数据吗？这将覆盖您当前的所有记录！')) {
        // 重置文件选择框
        importFile.value = '';
        return;
    }
    
    const reader = new FileReader();
    
    reader.onload = function(event) {
        try {
            // 解析JSON数据
            const importedData = JSON.parse(event.target.result);
            
            // 验证数据结构
            if (!importedData.todos || !importedData.dailyTasks || !importedData.tags) {
                throw new Error('无效的数据格式');
            }
            
            // 更新应用数据
            todos = importedData.todos;
            dailyTasks = importedData.dailyTasks;
            tags = importedData.tags;
            
            // 保存到本地存储
            saveData();
            
            // 刷新所有视图
            updateDateDisplay();
            updateMonthDisplay();
            renderTodoList();
            renderWorkTags();
            renderDailyWorkList();
            renderCalendar();
            renderFilterTags();
            renderMonthlyRecords();
            updateMonthlyStats();
            renderTagList();
            
            alert('数据导入成功！');
        } catch (error) {
            alert('导入失败：' + error.message);
        } finally {
            // 重置文件选择框
            importFile.value = '';
        }
    };
    
    reader.readAsText(file);
}

// 启动应用
initApp();